package com.csjbot.snowbot_rogue.services;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.display.DisplayManager;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;

import com.csjbot.csjbase.base.CsjBaseService;
import com.csjbot.csjbase.log.Csjlogger;
import com.csjbot.snowbot_rogue.Events.EventsConstants;
import com.csjbot.snowbot_rogue.Events.ExpressionEvent;
import com.csjbot.snowbot_rogue.R;
import com.csjbot.snowbot_rogue.utils.Constant;
import com.expression.uartagent.ExpressionUartAgent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Random;

/**
 * Created by RYX on 2016/6/24.
 */
public class BackgroundPlayService extends CsjBaseService implements DisplayManager.DisplayListener {
    private ImageView presentImageView, expressionImageView;
    private MyPresentation myPresentation;

    private DisplayManager mDisplayManager;
    private static final int CHECK_DISPLAY_TIME = 2000;
    private ExpressionUartAgent expressionAgent;
    private int recoverTime = 5000;

    private final static String SERVICE_ACTION = "com.csjbot.face";

    private int anim_face_angry = R.drawable.anim_face_angry,// 440ms
            anim_face_normal = R.drawable.anim_face_blink,// 1430ms
            anim_face_happy = R.drawable.anim_face_happy,// 1440ms
            anim_face_sorrow = R.drawable.anim_face_sorrow,// 480ms
            anim_face_afraid = R.drawable.anim_face_afraid,// 900ms
            anim_face_amazing = R.drawable.anim_face_amazing,// 1800ms
            anim_face_speak = R.drawable.anim_face_speak,// 1620ms
            anim_face_shy = R.drawable.anim_face_shy,// 1300ms
            anim_face_sleep = R.drawable.anim_face_sleep,// 3150ms
            anim_face_queries = R.drawable.anim_face_queries;// 2050ms

    private int[] faces = new int[]{anim_face_angry, anim_face_normal, anim_face_speak};

    private void changeExpression(int expressionType) {
        if (expressionAgent != null) {
//            expressionAgent.sendMessage(new UartPacketExpression(expressionType));
        }
    }

    private void sleep() {
        if (presentImageView != null) {
            presentImageView.setBackgroundResource(anim_face_sleep);
            ((AnimationDrawable) presentImageView.getBackground()).start();
        }
    }

    private void shy() {
        if (presentImageView != null) {
            presentImageView.setBackgroundResource(anim_face_shy);
            ((AnimationDrawable) presentImageView.getBackground()).start();
        }
    }

    private void queries() {
        if (presentImageView != null) {
            presentImageView.setBackgroundResource(anim_face_queries);
            ((AnimationDrawable) presentImageView.getBackground()).start();
        }
    }

    private void amazing() {
        if (presentImageView != null) {
            presentImageView.setBackgroundResource(anim_face_amazing);
            ((AnimationDrawable) presentImageView.getBackground()).start();
        }
    }

    private void afraid() {
        if (presentImageView != null) {
            presentImageView.setBackgroundResource(anim_face_afraid);
            ((AnimationDrawable) presentImageView.getBackground()).start();
        }
    }

    public void speak() {
        if (presentImageView != null) {
            presentImageView.setBackgroundResource(anim_face_speak);
            ((AnimationDrawable) presentImageView.getBackground()).start();
        }
    }

    public void angry() {
        if (presentImageView != null) {
            presentImageView.setBackgroundResource(anim_face_angry);
            ((AnimationDrawable) presentImageView.getBackground()).start();
        }
    }

    // TODO 随机决定是否眨两下眼睛
    private Runnable normalFaceRunable = new Runnable() {
        @Override
        public void run() {

        }
    };

    public void normal() {
        if (presentImageView != null) {
            presentImageView.setBackgroundResource(anim_face_normal);
            ((AnimationDrawable) presentImageView.getBackground()).start();
        }
    }

    private void sorrow() {
        if (presentImageView != null) {
            presentImageView.setBackgroundResource(anim_face_sorrow);
            ((AnimationDrawable) presentImageView.getBackground()).start();
        }
    }

    private void happy() {
        if (presentImageView != null) {
            presentImageView.setBackgroundResource(anim_face_happy);
            ((AnimationDrawable) presentImageView.getBackground()).start();
        }
    }

    private BroadcastReceiver changeExpressionColorReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (expressionImageView != null) {
                int color = intent.getIntExtra("color", Color.parseColor("#ff000000"));
                expressionImageView.setBackgroundColor(color);
            }
        }
    };

    @Override
    public boolean useEventBus() {
        return true;
    }

    private void changeExpressionColorReceiver(int colorInt) {
        if (expressionImageView != null) {
            expressionImageView.setBackgroundColor(colorInt);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Csjlogger.debug("BackgroundPlayService onStartCommand ");
        return super.onStartCommand(intent, flags, startId);
    }

    Handler mHandler = new Handler();

    private Runnable faceTestRunnable = new Runnable() {
        @Override
        public void run() {
            if (presentImageView != null) {
                int anim = faces[new Random().nextInt(faces.length - 1)];
                presentImageView.setBackgroundResource(anim);
                ((AnimationDrawable) presentImageView.getBackground()).start();
                mHandler.postDelayed(this, 5000);
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        Csjlogger.debug("BackgroundPlayService onCreate ");
        mDisplayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
        Display[] displays = mDisplayManager.getDisplays();
        mDisplayManager.registerDisplayListener(this, mHandler);
        Csjlogger.debug("registerDisplayListener ");

//        updateContents();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                updateContents();
            }
        }, 100);

//        expressionAgent = ExpressionUartAgent.createExpressionUartAgent(this, EmUartAgentType.emNormalUartagent, "/dev/ttyS1", 115200, new EventListener() {
//            @Override
//            public void onEvent(ClientEvent clientEvent) {
//
//            }
//        });

        //测试代码
//        new Thread(new Runnable() {
//
//            private int expression = 0;
//
//            @Override
//            public void run() {
//                while (true)
//                {
//                    if (expression > 9)
//                    {
//                        expression = 0;
//                    }
//                    CsjLog.d("test", "expression is " + expression);
//                    changeExpression(expression);
//                    expression++;
//                    try {
//                        Thread.sleep(3000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//
//        }).start();
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void initViewSurface() {
        Csjlogger.debug("initViewSurface");
        WindowManager mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        // 获取LayoutParams对象
        WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
        wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        wmParams.format = PixelFormat.RGBA_8888;
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;
        wmParams.x = 0;
        wmParams.y = 0;
        // 宽度和高度为0, 可以避免主屏退出后出现的主屏触摸和点击问题。
        wmParams.width = 0;
        wmParams.height = 0;
        LayoutInflater inflater = LayoutInflater.from(this);
        ViewGroup presentationLayout = (ViewGroup) inflater.inflate(R.layout.presentation_layout, null);
        presentationLayout.setFocusable(false);
        mWindowManager.addView(presentationLayout, wmParams);
    }


    // 获取显示设备。
    public void updateContents() {
        initViewSurface();

        Display[] displays = mDisplayManager.getDisplays();
        Csjlogger.debug("updateContents " + displays.length);
        try {
            if (displays.length > 1) {
                showPresentation(displays[1]);
            }
        } catch (IllegalStateException e) {
            Csjlogger.error(e.getMessage());
        }
    }

    private Runnable resetRunable = new Runnable() {
        @Override
        public void run() {
//            if (myPresentation != null && !myPresentation.isShowing()) {
            updateContents();
//            }
            Csjlogger.debug("resetRunable");
//            mHandler.postDelayed(this, CHECK_DISPLAY_TIME);
        }
    };


    // 将内容显示到display上面。
    private void showPresentation(Display display) {
        myPresentation = new MyPresentation(this, display);
        myPresentation.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                Csjlogger.debug("myPresentation  onDismiss");
                mHandler.postDelayed(resetRunable, CHECK_DISPLAY_TIME);
            }
        });

        myPresentation.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                Csjlogger.debug("myPresentation  onShow");
                changeExpression(Constant.Expression.EXPRESSION_NORMAL);
                normal();
                mHandler.removeCallbacks(resetRunable);
            }
        });

        Csjlogger.debug("myPresentation ");

        myPresentation.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);
        myPresentation.show();
        presentImageView = myPresentation.getImageView();
        expressionImageView = myPresentation.getExpressionBackgroud();
//        mHandler.postDelayed(resetRunable, CHECK_DISPLAY_TIME);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeExpression(ExpressionEvent event) {
        switch (event.getTag()) {
            /**
             * private int anim_face_angry = R.drawable.anim_face_angry,// 440ms
             anim_face_normal = R.drawable.anim_face_blink,// 1430ms
             anim_face_happy = R.drawable.anim_face_happy,// 1440ms
             anim_face_sorrow = R.drawable.anim_face_sorrow,// 480ms
             anim_face_afraid = R.drawable.anim_face_afraid,// 900ms
             anim_face_amazing = R.drawable.anim_face_amazing,// 1800ms
             anim_face_speak = R.drawable.anim_face_speak,// 1620ms
             anim_face_shy = R.drawable.anim_face_shy,// 1300ms
             anim_face_sleep = R.drawable.anim_face_sleep,// 3150ms
             anim_face_queries = R.drawable.anim_face_queries;// 2050ms
             */
            case EventsConstants.ExpressionEvent.ACTION_CHANGE_FACE_COLOR:
                changeExpressionColorReceiver((Integer) event.data);
                break;
            case Constant.Expression.EXPRESSION_NORMAL:
                changeExpression(Constant.Expression.EXPRESSION_NORMAL);
                normal();
                break;
            case Constant.Expression.EXPRESSION_HAPPY:
                changeExpression(Constant.Expression.EXPRESSION_HAPPY);
                happy();
                changeExpressionNormal(2440);
                break;
            case Constant.Expression.EXPRESSION_SPEAK:
                changeExpression(Constant.Expression.EXPRESSION_SPEAK);
                speak();
                break;
            case Constant.Expression.EXPRESSION_ANGRY:
                changeExpression(Constant.Expression.EXPRESSION_ANGRY);
                angry();
                changeExpressionNormal(1440);
                break;
            case Constant.Expression.EXPRESSION_SORROW:
                changeExpression(Constant.Expression.EXPRESSION_SORROW);
                sorrow();
                changeExpressionNormal(1480);
                break;
            case Constant.Expression.EXPRESSION_AFRAID:
                changeExpression(Constant.Expression.EXPRESSION_AFRAID);
                afraid();
                changeExpressionNormal(1900);
                break;
            case Constant.Expression.EXPRESSION_AMAZING:
                changeExpression(Constant.Expression.EXPRESSION_AMAZING);
                amazing();
                changeExpressionNormal(2800);
                break;
            case Constant.Expression.EXPRESSION_QUERIES:
                changeExpression(Constant.Expression.EXPRESSION_QUERIES);
                queries();
                changeExpressionNormal(3050);
                break;
            case Constant.Expression.EXPRESSION_SHY:
                changeExpression(Constant.Expression.EXPRESSION_SHY);
                shy();
                changeExpressionNormal(2300);
                break;
            case Constant.Expression.EXPRESSION_SLEEP:
                changeExpression(Constant.Expression.EXPRESSION_SLEEP);
                sleep();
                break;
            default:
                break;
        }
    }

    public void setRecoverTime(int time) {
        this.recoverTime = time;
    }

    public int getRecoverTime() {
        return this.recoverTime;
    }

    private void changeExpressionNormal(int delay) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                changeExpression(new ExpressionEvent(Constant.Expression.EXPRESSION_NORMAL));
            }
        }, delay);
    }

    @Override
    public void onDisplayAdded(int displayId) {
        Csjlogger.debug("onDisplayAdded");
        mHandler.postDelayed(resetRunable, CHECK_DISPLAY_TIME);
    }

    @Override
    public void onDisplayRemoved(int displayId) {
        Csjlogger.debug("onDisplayRemoved");
//        mHandler.postDelayed(resetRunable, CHECK_DISPLAY_TIME);
    }

    @Override
    public void onDisplayChanged(int displayId) {
        Csjlogger.debug("onDisplayChanged");
    }
}
